// 接收 chargen 发送的数据。
#include <muduo/base/Logging.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/InetAddress.h>
#include <muduo/net/TcpClient.h>
#include <boost/bind.hpp>
#include <stdio.h>

using namespace muduo;
using namespace muduo::net;

class ChargenClient : boost::noncopyable {
public:
	ChargenClient(EventLoop *loop, const InetAddress &serverAddr)
		: loop_(loop), client_(loop, serverAddr, "ChargenClient") {
		client_.setConnectionCallback(boost::bind(&ChargenClient::OnConnection, this, _1));
		client_.setMessageCallback(boost::bind(&ChargenClient::OnMessage, this, _1, _2, _3));
		// client_.enableRetry();
	}

	void Connect() {
		client_.connect();
	}

private:
	void OnConnection(const TcpConnectionPtr &conn) {
		LOG_INFO << conn->localAddress().toIpPort() << " -> "
		         << conn->peerAddress().toIpPort() << " is "
		         << (conn->connected() ? "UP" : "DOWN");
		if (!conn->connected())
			loop_->quit();
	}

	void OnMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp receiveTime) {
		buf->retrieveAll();
	}

	EventLoop *loop_;
	TcpClient client_;
};

int
main(int argc, char **argv) {
	LOG_INFO << "pid = " << getpid();
	if (argc > 1) {
		EventLoop loop;
		InetAddress serverAddr(argv[1], 2019);
		ChargenClient chargenClient(&loop, serverAddr);
		chargenClient.Connect();
		loop.loop();
	} else {
		printf("Usage: %s host_ip\n", argv[0]);
	}
}
